   // pages/login/login.js
var App = getApp();
const utils = require('../../utils/util.js');
var openId = '';
Page({

  /**
   * 页面的初始数据
   */
  data: {
    yzmStatus:'获取验证码',
    getYzm:false,
    canLogin:false,
    userName:'',
    userYzm:'',
    yzmBtnUse:true,//验证码按钮是否可点击
    inviteId: ''
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    //扫二维码进去的时候获取二维码的信
    // if (options.q) {
    //   let qrUrl = decodeURIComponent(options.q);//获取二维码的携带的链接信息
    //   console.log(qrUrl)
    // }

    if (options.invite!=undefined){ //有邀请码
      this.setData({
        inviteId: options.invite
      })
    }
    wx.removeStorageSync('location');
    wx.removeStorageSync('city');
    this.autoLocation();//定位
  },
  // 自动定位
  autoLocation:function(){
    const that = this;
    wx.getLocation({
      type: 'wgs84',
      success(res) {
        console.log(res)
        const latitude = res.latitude //纬度
        const longitude = res.longitude //经度
        const accuracy = res.accuracy;

        // const latitude = '30.52' //武汉纬度
        // const longitude = '114.31' //经度
        wx.setStorageSync('location', longitude + ',' + latitude)

      },
      complete:function(res){
        that.getWxUserinfo();//获取用户的openid();
      }
    })
  },
  getUserCity:function(){
    if(wx.getStorageSync('location')==''){
      return false;
    }
    wx.request({
      url: App.data.globalAPI + '/search/index/nearestschool',
      data: {
        token: wx.getStorageSync('token'),
        location: wx.getStorageSync('location'), //经度在前，纬度在后
        type: 'gps'
      },
      header: {
        'content-type': 'application/json' // 默认值
      },
      success(res2) {
        const nearest = res2.data.data.nearest;
        const floors = res2.data.data.floors;
        if (res2.data.error == 0) {
          wx.setStorageSync('city', nearest.city);

        } else {
          wx.showToast({
            title: res2.data.msg,
            icon: 'none',
            duration: 800
          })
        }
      }
    })
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
  
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
  
  },


  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {
  
  },
  //绑定手机号
  bindUserName:function(e){
    this.setData({
      userName: e.detail.value
    })
    if (this.data.userYzm.length == 4 && this.data.userName.length == 11) {
      this.setData({
        canLogin: true
      })
    } else {
      this.setData({
        canLogin: false
      })
    }
  },
  clearNameMsg:function(){
    this.setData({
      userName:''
    })
  },
  // 绑定验证码输入框
  bindUserYzm:function(e){
    this.setData({
      // userYzm: e.detail.value.replace(/\D/g, '')
      userYzm: e.detail.value
    })
    if (this.data.userYzm.length == 4 && this.data.userName.length==11){
      this.setData({
        canLogin:true
      })
    }else{
      this.setData({
        canLogin: false
      })
    }
  },
  // 获取验证码
  getYzmHandle:function(){
    let that = this;
    if (that.data.userName == '' && that.data.yzmStatus.indexOf('秒') < 0){
      wx.showToast({
        title: '请输入手机号',
        icon: 'none',
        duration: 1000
      })
    } else if (that.data.yzmStatus.indexOf('秒') >-1){
      wx.showToast({
        title: '短信发送中，请勿重复提交',
        icon: 'none',
        duration: 800
      })
    }
    else{
      
      var isPhone = App.isPhoneAvailable(that.data.userName);//手机号正则判断
      if (isPhone && that.data.yzmBtnUse ){
        let time = 60;
        that.setData({
          yzmBtnUse:false
        })
        wx.request({
          url: App.data.globalAPI + '/users/login/smscode',
          data: {
            phone: that.data.userName,//电话号码
          },
          header: {
            'content-type': 'application/json' // 默认值
          },
          success(res) {
            if (res.data.error == 0) {
              wx.showToast({
                title: '验证码已发送，请注意查收！',
                icon: 'none',
                duration: 800
              })
              var stopTime = setInterval(function () {
                time--;
                that.setData({
                  yzmStatus: time + '秒后重发',
                  getYzm: true,
                })
                if (time == 0) {
                  clearInterval(stopTime);
                  that.setData({
                    yzmStatus: '重新获取',
                    getYzm: false,
                    yzmBtnUse: true
                  })
                }
              }, 1000)
            }else{
              wx.showToast({
                title: res.data.msg,
                icon: 'none',
                duration: 800
              })
            }
            
          }, fail(res) {
            wx.showModal({
              title: '提示',
              content: '网络异常，请稍后重试！',
              showCancel: false,
              success(res) {

              }
            })
            that.setData({
              yzmBtnUse: true
            })
          }
        })     
      }
    }

  },
  // 提交登录信息
  commitLogin:function(){
    console.log(this.data.inviteId)
    if (this.data.canLogin){
      let that = this;
      wx.request({
        url: App.data.globalAPI + '/users/login/login',
        data: {
          openid: openId,
          phone: that.data.userName,//电话号码
          validate_code: that.data.userYzm,//验证码
          token: '',//token
          source: 'small program',//注册来源标识
          imei: '',	//设备标识
          idfv: '',	//设备标识
          invite_id: that.data.inviteId == '' ? '' : that.data.inviteId//邀请人标识
        },
        header: {
          'content-type': 'application/json' // 默认值
        },
        success(res) {
          if(res.data.error == 0){
            wx.showToast({
              title: '登录成功',
              icon: 'success',
              duration: 1000
            })
            setTimeout(function () {
              wx.reLaunch({
                url: '../index/index'
              })
            }, 800)
            wx.setStorageSync('token', res.data.data.token);
            wx.setStorageSync('userInfo', res.data.data.userinfo);
            wx.setStorageSync('allUserMsg', res.data.data);

            that.getUserCity();//获取授权城市信息
          }else{
            wx.showToast({
              title: res.data.msg,
              icon: 'none',
              duration: 800
            })
          }
          
        },
        fail(res) {
          wx.showModal({
            title: '提示',
            content: '网络异常，请稍后重试！',
            showCancel: false,
            success(res) {

            }
          })
        
        }
      }) 
    }
  },
  // 高校代理登录
  highSchoolLogin:function(){
    wx.showModal({
      title: '登录提示',
      content: '高校代理请下载客户端登录',
      showCancel:false,
      success(res) {
        if (res.confirm) {
          console.log('用户点击确定')
        } 
      }
    })
  },
  autoCerviryLogin:function(){
    const that = this;
    //验证登录
    if (wx.getStorageSync('token') != '') {
      wx.request({
        url: App.data.globalAPI + '/users/login/login',
        data: {
          token: wx.getStorageSync('token'),//token
          openid: openId
        },
        header: {
          'content-type': 'application/json' // 默认值
        },
        success(res) {
          if (res.data.error == 0) {
            
            wx.showToast({
              title: '自动登录成功',
              icon: 'success',
              duration: 500
            })
            setTimeout(function () {
              wx.reLaunch({
                url: '../index/index'
              })
            }, 600)
            wx.setStorageSync('token', res.data.data.token);
            wx.setStorageSync('userInfo', res.data.data.userinfo);
            wx.setStorageSync('allUserMsg', res.data.data);

            that.getUserCity();//获取授权城市信息
          } else {
            wx.showToast({
              title: res.data.msg,
              icon: 'none',
              duration: 800
            })
            
          }
        }
      })
    }
  },
  //获取用户的openid
  getWxUserinfo: function(){
    const that = this;
    wx.login({
      success: function (res) {
        //发送请求
        wx.request({
          url: App.data.globalAPI +'/users/weixin/openid', //接口地址
          data: {
            code: res.code,
            type: 'lite' 
          },
          header: {
            'content-type': 'application/json' //默认值
          },
          success: function (res) {
            if(res.data.error == 0 ){
              openId = res.data.data.openid;
              // that.autoCerviryLogin()
            }
          }
        })
      }
    })
  }

})
